/**
 * table-sort.js
 * 
 * I should work on my js-doc skills :x
 */
$(document).ready(function(){

    $('table.sortable th').wrapInner('<a></a>');
    //wrap th contents in <a></a> for better styling
    
//    $.('table.sortable').wrap('<div class="table-wrap"></div>)');
    //wrap tables in 'table-wrap
    
    $('table.sortable th a').bind('click', function(e) {
        //watch clicks on th links
        
        var th = $(e.target).parents('th');
        //the th element

        var table = th.parents('table');
        //the whole table

        table.parents('.table-wrap').block({
            message: 'Loading...'
        });
        //block the table
        
        var classes = th.attr('class').split(' ');
        var sort = classes.shift();
        //column to sort on

        var dir = 'desc';
        if (th.hasClass('desc')) {
        	//we already had a desc class
        	dir = 'asc';
        }
        //sort direction
        
        table.find('th').removeClass('desc').removeClass('asc');
        //remove all desc/asc from other th's
        
        th.addClass(dir);
        //add the proper dir to the click-ed th
        
    	
        var type = table.attr('class').split(' ').shift();
        //classname of the table corresponds to type

        var url = '/admin/' + type + '/table/sort/' + sort + '/dir/' + dir + '/';
        //where can we find the table? :D
        
        table.children('tbody').load(url, null, function() {
    		table.parents('.table-wrap').unblock();
    	});
    
        return false;
    });
    
});